package com.course.server.service;

import cn.hutool.core.util.StrUtil;
import com.course.server.dto.ChapterDto;
import com.course.server.dto.PageDto;
import com.course.server.entity.Chapter;
import com.course.server.entity.ChapterExample;
import com.course.server.mapper.ChapterMapper;
import com.course.server.util.CopyUtil;
import com.course.server.util.UuidUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Durian
 * @date: 2021/4/18 18:26
 */
@Service
public class ChapterService {

    @Resource
    private ChapterMapper chapterMapper;

    public PageDto<ChapterDto> list(int page, int size, String courseId) {
        PageHelper.startPage(page, size);
        ChapterExample example = new ChapterExample();
        // criteria只能一次
        ChapterExample.Criteria criteria = example.createCriteria();
        // service层尽量灵活
        if (StrUtil.isNotBlank(courseId)) {
            criteria.andCourseIdEqualTo(courseId);
        }
        List<Chapter> chapters = chapterMapper.selectByExample(example);
        PageInfo<Chapter> pageInfo = new PageInfo<>(chapters);

        List<ChapterDto> chapterDtos = CopyUtil.copyList(chapters, ChapterDto.class);
        PageDto<ChapterDto> pageDto = new PageDto<>();
        pageDto.setPage(page);
        pageDto.setSize(size);
        pageDto.setList(chapterDtos);
        pageDto.setTotal(pageInfo.getTotal());
        return pageDto;
    }

    public void save(ChapterDto chapterDto) {
        Chapter chapter = new Chapter();
        BeanUtils.copyProperties(chapterDto, chapter);
        if (StrUtil.isBlank(chapterDto.getId())) {
            insert(chapter);
        } else {
            update(chapter);
        }
    }

    public void delete(String id) {
        chapterMapper.deleteByPrimaryKey(id);
    }

    private void insert(Chapter chapter) {
        chapter.setId(UuidUtils.getShortUuid());
        chapterMapper.insert(chapter);
    }

    private void update(Chapter chapter) {
        chapterMapper.updateByPrimaryKeySelective(chapter);
    }

}
